package br.com.gkarian.mydesk.tag;

import java.io.IOException;
import java.text.NumberFormat;
import java.util.Locale;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;

public class ValorFormatterTag extends SimpleTagSupport {

	/** valor em centavos */
	private String valor;

	private NumberFormat numberFormat = NumberFormat
			.getNumberInstance(new Locale("pt", "BR"));

	public ValorFormatterTag() {
		numberFormat.setMaximumFractionDigits(2);
		numberFormat.setMinimumFractionDigits(2);
		numberFormat.setGroupingUsed(true);
	}

	public void doTag() throws JspException, IOException {
		getJspContext().getOut().print(formatar(valor));
	}

	public String getValor() {
		return valor;
	}

	public void setValor(String valor) {
		this.valor = valor;
	}

	private String formatar(String valor) {
		if (valor == null) {
			return null;
		}
		try {
			valor = numberFormat.format(Long.parseLong(valor) / 100.0);
		} catch (Exception e) {
			valor = "0";
		}

		return valor;
	}
}
